package com.ease.integration.ftp;

import java.io.File;

import com.ease.common.util.Assertion;

public class FtpTemplate {

	private FtpClient ftpClient;

	protected boolean connect() throws RuntimeException {
		Assertion.notNull(ftpClient, "ftp not found");
		boolean result = true;
		result = ftpClient.connect();
		return result;
	}

	protected boolean disconnect() throws RuntimeException {
		Assertion.notNull(ftpClient, "ftp not found");
		return ftpClient.disconnect();
	}

	protected <T> T execute(FtpExecutionCallback<T> ftpExecutionCallback) throws RuntimeException {
		try {
			this.connect();

			return ftpExecutionCallback.execute();

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			this.disconnect();
		}
	}

	public void upload(final String remoteDirectory, final File file) throws RuntimeException {

		this.execute(new FtpExecutionCallback<Object>() {
			public Object execute() throws Exception {
				if (file.isDirectory()) {
					ftpClient.uploadDirectory(remoteDirectory, file);
				} else {
					ftpClient.uploadFile(remoteDirectory, file);
				}
				return null;
			}

		});
	}

	public boolean download(final String remoteDirectory, final String remoteFileName, final String localDirectory) throws RuntimeException {
		return this.execute(new FtpExecutionCallback<Boolean>() {
			public Boolean execute() throws Exception {
				return ftpClient.downloadFile(remoteDirectory, remoteFileName, localDirectory, remoteFileName);
			}
		});
	}

	public boolean download(final String remoteDirectory, final String remoteFileName, final String localDirectory, final String localFileName) throws RuntimeException {
		return this.execute(new FtpExecutionCallback<Boolean>() {
			public Boolean execute() throws Exception {
				return ftpClient.downloadFile(remoteDirectory, remoteFileName, localDirectory, localFileName);
			}
		});
	}

	public boolean has(final String remoteDirectory, final String fileName) {
		return this.execute(new FtpExecutionCallback<Boolean>() {
			public Boolean execute() throws Exception {
				return ftpClient.hasFile(remoteDirectory, fileName);
			}
		});
	}

	public boolean remove(final String remoteDirectory, final String fileName) {
		return this.execute(new FtpExecutionCallback<Boolean>() {
			public Boolean execute() throws Exception {
				return ftpClient.remove(remoteDirectory, fileName);
			}
		});
	}

	public void list(final String remoteDirectory) {

	}

	public void mlist(final String remoteDirectory) {

	}

	/**
	 * @return the ftpClient
	 */
	public FtpClient getFtpClient() {
		return ftpClient;
	}

	/**
	 * @param ftpClient
	 *            the ftpClient to set
	 */
	public void setFtpClient(FtpClient ftpClient) {
		this.ftpClient = ftpClient;
	}

}
